<template>
  <div class="app-container">
    <!--条件搜索表单-->
    <el-row :gutter="20">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="searchObj.jobName" placeholder="任务名称" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchObj.jobGroup" placeholder="任务组" clearable @change="getAll()">
            <el-option v-for="item in jobGroupOptions" :key="item.value" :label="`${item.label} [${item.value}]`" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchObj.status" placeholder="任务状态" clearable @change="getAll()">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="getAll()">查询</el-button>
        <el-button icon="el-icon-refresh" @click="reset()">清空</el-button>
      </el-form>
    </el-row>

    <el-row :gutter="20">
      <el-button v-if="hasPerm('monitor:job:save')" type="primary" icon="el-icon-plus" @click="openEdit(null)">新增</el-button>
      <el-button v-if="hasPerm('monitor:job:batch-delete')" type="danger" icon="el-icon-delete" :disabled="ids.length < 1" @click="batchDelete">
        批量删除
      </el-button>
    </el-row>

    <el-divider />

    <el-row :gutter="20">
      <div v-for="item in page.records" :key="item.id">
        <el-col :xs="20" :sm="20" :md="12" :lg="8" :xl="6">
          <el-card style="margin-bottom: 25px" shadow="hover">
            <div slot="header">
              <el-checkbox :model="item.selected" @change="jobChangeHandler(item)">
                <b>{{ item.jobName }}</b>
              </el-checkbox>
            </div>
            <div>
              <p>任务组名: {{ item.jobGroup }}</p>
              <p>
                任务状态:
                <el-tag v-if="item.status == 0" type="success">运行中</el-tag>
                <el-tag v-if="item.status == 1" type="warning">未发布</el-tag>
                <el-tag v-if="item.status == 2" type="info">未启动</el-tag>
              </p>
              <p>cron表达式: {{ item.cronExpression }}</p>
              <p>调用目标: {{ item.invokeTarget }}</p>
              <p>创建时间: {{ item.createTime }}</p>
            </div>
            <el-divider />
            <div style="text-align: center">
              <el-link v-if="hasPerm('monitor:job-log:page')" type="info" icon="el-icon-info" @click="openLog(item)">日志</el-link>
              <el-divider v-if="hasPerm('monitor:job:start', 'monitor:job:pause')" direction="vertical" />
              <el-link v-if="hasPerm('monitor:job:start') && item.status !== 0" type="primary" icon="el-icon-video-play" @click="executeJob(item, 1)">
                启动
              </el-link>
              <el-link v-if="hasPerm('monitor:job:pause') && item.status == 0" type="warning" icon="el-icon-video-pause" @click="executeJob(item, 2)">
                暂停
              </el-link>
              <el-divider v-if="hasPerm('monitor:job:start', 'monitor:job:pause')" direction="vertical" />
              <el-link v-if="hasPerm('monitor:job:run')" type="primary" icon="el-icon-refresh-right" @click="executeJob(item, 0)">执行</el-link>
              <el-divider v-if="hasPerm('monitor:job:update')" direction="vertical" />
              <el-link v-if="hasPerm('monitor:job:update')" type="success" icon="el-icon-edit" @click="openEdit(item)">修改</el-link>
              <el-divider v-if="hasPerm('monitor:job:delete')" direction="vertical" />
              <el-link v-if="hasPerm('monitor:job:delete')" type="danger" icon="el-icon-remove" @click="remove(item.id)">删除</el-link>
              <el-divider direction="vertical" />
              <el-link type="info" icon="el-icon-view" @click="openDetail(item)">详情</el-link>
            </div>
          </el-card>
        </el-col>
      </div>
    </el-row>

    <el-divider />

    <!-- 分页导航栏 -->
    <div>
      <el-pagination
        :background="true"
        :current-page="pIndex"
        :page-size="pSize"
        :total="page.total"
        :page-sizes="[1, 3, 6, 9, 12, 15, 18]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        @current-change="getAll"
        @size-change="handleSizeChange"
      />
    </div>

    <!-- 表单 -->
    <el-dialog v-if="hasPerm('monitor:job:save', 'monitor:job:update')" :title="dialogTitle" :visible.sync="visible" @close="close('jobForm')">
      <el-form ref="jobForm" :model="job" :rules="rules" label-width="100px">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="ID" prop="id" :hidden="true">
              <el-input v-model="job.id" disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="任务名称" prop="jobName" required>
              <el-input v-model="job.jobName" placeholder="请输入任务名称" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="任务组名" prop="jobGroup" required>
              <el-select v-model="job.jobGroup" placeholder="请选择任务组" style="width: 100%">
                <el-option v-for="item in jobGroupOptions" :key="item.value" :label="`${item.label} [${item.value}]`" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="12">
            <el-form-item label="调用目标" prop="invokeTarget" required>
              <el-input v-model="job.invokeTarget" placeholder="请输入调用目标" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="执行策略" prop="misfirePolicy">
              <el-select v-model="job.misfirePolicy" placeholder="请选择执行策略" style="width: 100%">
                <el-option v-for="item in misfirePolicyOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="12">
            <el-form-item label="cron表达式" prop="cronExpression" required>
              <el-input v-model="job.cronExpression" placeholder="请输入cron表达式">
                <el-button slot="append" @click="showCrontab = true">生成cron</el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="是否并发" prop="concurrent">
              <el-select v-model="job.concurrent" placeholder="请选择是否并发" style="width: 100%">
                <el-option v-for="item in concurrentOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="排序" prop="priority">
              <el-input-number v-model.number="job.priority" controls-position="right" placeholder="请输入排序" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="任务备注" prop="remark">
              <el-input v-model="job.remark" :rows="3" type="textarea" placeholder="请输入备注" maxlength="255" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="close('jobForm')">取 消</el-button>
        <el-button type="primary" @click="save('jobForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 详情 -->
    <el-dialog title="任务详情" :visible.sync="detailVisible" @close="detailVisible = false">
      <el-form :model="job" label-width="120px">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="任务名称"> {{ job.jobName }} </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="任务组名"> {{ job.jobGroup }} </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form-item label="调用目标">{{ job.invokeTarget }} </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="cron表达式">{{ job.cronExpression }} </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="cron执行策略">
              <template v-for="item in misfirePolicyOptions">
                <el-tag v-if="item.value == job.misfirePolicy" :key="item.value" type="success">{{ item.label }}</el-tag>
              </template>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="是否并发">
              <template v-for="item in concurrentOptions">
                <el-tag v-if="item.value == job.concurrent" :key="item.value">{{ item.label }}</el-tag>
              </template>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="下次执行时间"> {{ job.nextExecTime }} </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="任务状态">
              <el-tag v-if="job.status == 0" type="success">运行中</el-tag>
              <el-tag v-if="job.status == 1" type="warning">未发布</el-tag>
              <el-tag v-if="job.status == 2" type="info">未启动</el-tag>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="优先级"> {{ job.priority }} </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-form-item label="创建时间"> {{ job.createTime }} </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="任务备注"> {{ job.remark }} </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="detailVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- cron -->
    <el-dialog title="生成Cron" :visible.sync="showCrontab" @close="showCrontab = false">
      <vcrontab :expression="job.cronExpression" @hide="showCrontab = false" @fill="crontabFill" />
    </el-dialog>

    <!-- 执行日志 -->
    <JobLog v-if="hasPerm('monitor:job-log:page') && jobLogVisible" :job-name="job.jobName" @close="jobLogVisible = false" />
  </div>
</template>

<script>
// 引入api接口定义的js文件
import jobApi from '@/api/sys/job'
import dictItemApi from '@/api/sys/dict-item'

import Vcrontab from 'vcrontab'
import JobLog from './job-log'

export default {
  // 组件
  components: { Vcrontab, JobLog },
  data() {
    // 定义变量和初始值
    return {
      // 状态选项
      statusOptions: [
        { value: 0, label: '运行中' },
        { value: 1, label: '已暂停' },
        { value: 2, label: '未启动' }
      ],
      // cron执行策略选项
      misfirePolicyOptions: [
        { value: 1, label: '立即执行' },
        { value: 2, label: '执行一次' },
        { value: 3, label: '放弃执行' }
      ],
      // 是否并发选项
      concurrentOptions: [
        { value: 0, label: '允许' },
        { value: 1, label: '禁止' }
      ],

      // 查询条件
      searchObj: {},

      // 列表相关
      loading: false, // 加载状态
      pIndex: 1, // 当前页
      pSize: 6, // 每页显示记录数
      page: [], // 列表
      ids: [], // 选中的列ID

      // 表单相关
      dialogTitle: '',
      visible: false, // 是否显示表单
      job: {
        id: undefined,
        jobName: '',
        jobGroup: 'DEFAULT',
        invokeTarget: '',
        cronExpression: '',
        misfirePolicy: 3,
        concurrent: 1,
        status: 0,
        priority: 0,
        remark: ''
      },

      // 验证规则
      rules: {
        jobName: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
        invokeTarget: [{ required: true, message: '调用目标不能为空', trigger: 'blur' }],
        cronExpression: [{ required: true, message: 'corn 表达式不能为空', trigger: 'blur' }]
      },

      jobGroupOptions: [],

      // 生成 cron 表达式控制
      showCrontab: false,

      // 详情表单控制
      detailVisible: false,

      // 任务日志
      jobLogVisible: false
    }
  },
  created() {
    this.getAll()
    this.getJobGroup()
  },
  methods: {
    // 获取任务组
    getJobGroup() {
      dictItemApi.getListByDictCode('JOB_GROUP').then((res) => {
        this.jobGroupOptions = res.data
      })
    },

    // 加载列表数据
    getAll(current = 1) {
      this.loading = true
      this.pIndex = current
      jobApi
        .getPage(this.pIndex, this.pSize, this.searchObj)
        .then((response) => {
          this.page = response.data
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 改变页码
    handleSizeChange(pageSize) {
      this.pSize = pageSize
      // 重新调用数据加载方法 --> 方法中已经加入的查询参数
      this.getAll()
    },

    // cron 表达式
    crontabFill(val) {
      this.job.cronExpression = val
    },

    // 删除任务信息
    remove(id) {
      this.$confirm('此操作将永久删除任务信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          jobApi.deleteById(id).then((resp) => {
            this.$message.success('删除成功！')
            this.getAll()
          })
        })
        .catch(() => {
          this.$message.info('已取消删除！')
        })
    },

    // 复选框选中
    jobChangeHandler(job) {
      job.selected = !job.selected

      if (job.selected) {
        this.ids.push(job.id)
      } else {
        this.ids.splice(this.ids.indexOf(job.id), 1)
      }
    },

    executeJob(job, index) {
      const type = ['执行一次', '启动', '暂停']

      this.$confirm(`此操作将${type[index]} '${job.jobName}' 任务, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const appCall = index === 0 ? jobApi.runJob(job.id) : index === 1 ? jobApi.startJob(job.id) : index === 2 ? jobApi.pauseJob(job.id) : null
          appCall.then((res) => {
            this.$message.success('操作成功!')
            this.getAll()
          })
        })
        .catch(() => {
          this.$message.info('已取消！')
        })
    },

    // 打开表单页面
    openEdit(row) {
      this.dialogTitle = '新增任务'
      this.visible = true
      this.job.priority = this.page.total + 2

      if (row != null) {
        this.dialogTitle = '编辑任务'
        jobApi.getById(row.id).then((res) => {
          const data = res.data
          Object.assign(this.job, data)
          this.job.roleIds = data.roles.map((v) => v.id)
        })
      }
    },

    // 关闭表单
    close(form) {
      this.visible = false
      this.$refs[form].resetFields()
    },

    // 保存
    save(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          const apiCall = this.job.id ? jobApi.update(this.job) : jobApi.save(this.job)
          apiCall.then(() => {
            this.$message.success('操作成功')
            this.close(form)
            this.getAll()
          })
        }
      })
    },

    // 打开任务日志
    openLog(row) {
      this.jobLogVisible = true
      this.job = row
    },

    // 打开详情
    openDetail(row) {
      this.detailVisible = true
      this.job = row
    },

    // 批量删除
    batchDelete() {
      if (this.ids.length > 0) {
        this.$confirm('此操作将永久删除任务信息,是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          // 确定执行then方法
          .then(() => {
            jobApi.batchDelete(this.ids).then((resp) => {
              this.$message.success('删除成功！')
              this.getAll()
            })
          })
          .catch(() => {
            this.$message.info('已取消删除！')
          })
      } else {
        this.$message.warning('至少选择一条数据!')
      }
    },

    // 重置
    reset() {
      this.searchObj = {}
      this.getAll()
    }
  }
}
</script>

<style></style>
